import pandas as pd
import seaborn as sns
import matplotlib.pyplot as pltPandas: Intro to DataFrames
DataFrames are the core data structure in pandas for tabular data. This notebook covers creating DataFrames from various sources and basic operations.
You will learn how to: - Import essential libraries (Pandas, Seaborn, Matplotlib, NumPy) - Create DataFrames from dictionaries, lists, and NumPy arrays - View and manipulate DataFrames - Export DataFrames to CSV and Excel files
Importing Libraries
Start by importing pandas and other useful libraries for data analysis and visualization.
Creating DataFrames from Dictionaries
DataFrames can be created from Python dictionaries where keys become column names.
data = {'Name': ['Adil', 'Aman', 'Ziya', 'Zahra'],
'Age': [23,19,15,9],
'City': ['Matannur','Vellore', 'Tly', 'Knr' ]
}
data{'Name': ['Adil', 'Aman', 'Ziya', 'Zahra'],
'Age': [23, 19, 15, 9],
'City': ['Matannur', 'Vellore', 'Tly', 'Knr']}
df = pd.DataFrame(data)
df| Name | Age | City | |
|---|---|---|---|
| 0 | Adil | 23 | Matannur |
| 1 | Aman | 19 | Vellore |
| 2 | Ziya | 15 | Tly |
| 3 | Zahra | 9 | Knr |
Creating DataFrames from Lists
You can also create DataFrames from lists of lists, specifying column names.
data_list = [
['Adil', 23, 'Mattanur'],
['Aman', 19, 'Vellore'],
['Siraj', 55, 'Tly'],
['Faritha', 40, 'Chokli']
]
data_list[['Adil', 23, 'Mattanur'],
['Aman', 19, 'Vellore'],
['Siraj', 55, 'Tly'],
['Faritha', 40, 'Chokli']]
df_list = pd.DataFrame(data_list, columns=['Name', 'Age', 'City'])
df_list| Name | Age | City | |
|---|---|---|---|
| 0 | Adil | 23 | Mattanur |
| 1 | Aman | 19 | Vellore |
| 2 | Siraj | 55 | Tly |
| 3 | Faritha | 40 | Chokli |
Creating DataFrames from NumPy Arrays
Pandas integrates with NumPy; create DataFrames from arrays with column names.
import numpy as npdata_array = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
data_arrayarray([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
df_array = pd.DataFrame(data_array, columns=['A', 'B', 'C'])
df_array| A | B | C | |
|---|---|---|---|
| 0 | 1 | 2 | 3 |
| 1 | 4 | 5 | 6 |
| 2 | 7 | 8 | 9 |
Exporting DataFrames
Save DataFrames to files like CSV or Excel for sharing or further analysis.
df.to_csv('example.csv', index=False)df.to_excel('example.xlsx', index=False)Best Practices
- Use descriptive column names.
- Check data types with
df.dtypesafter creation. - Handle missing data appropriately.
Summary
This notebook introduced creating and exporting DataFrames. DataFrames are versatile for data manipulation—explore more operations next!